package com.etonenet.test.hazelcast.nearcache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.EvictionConfig;
import com.hazelcast.config.EvictionConfig.MaxSizePolicy;
import com.hazelcast.config.EvictionPolicy;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;

/**
 * 在客户端使用near Cache
 * <p>
 * <a href=
 * "http://docs.hazelcast.org/docs/3.5/manual/html-single/index.html#client-near-cache-configuration">
 * client-near-cache-configuration</a>
 * 
 * @author wxu
 *
 */
public class NearCacheClient {
	private final static Logger logger = LoggerFactory.getLogger(NearCacheClient.class);

	public static void main(String[] args) {
		new NearCacheClient();
	}

	private IMap<String, String> nearCacheMap;

	public NearCacheClient() {
		ClientConfig clientConfig = new ClientConfig();
		clientConfig.getGroupConfig().setName(Server.GROUP_NAME).setPassword(Server.GROUP_PASSWORD);

		//@formatter:off
		
		// near cache
		EvictionConfig evictionConfig = new EvictionConfig();
		evictionConfig.setMaximumSizePolicy(MaxSizePolicy.ENTRY_COUNT);
		evictionConfig.setEvictionPolicy(EvictionPolicy.LFU);
		evictionConfig.setSize(10000);
		NearCacheConfig nearCacheConfig = new NearCacheConfig()
				// 设置需要使用near Cache的map
				.setName("nearCacheMap")
				// 1 hour TTL
				.setTimeToLiveSeconds(60 * 60 * 1000)
				// 10 minutes max idle seconds
				.setMaxIdleSeconds(10 * 60 * 1000)
				// eviction
				.setEvictionConfig(evictionConfig);
		clientConfig.addNearCacheConfig(nearCacheConfig);
		
		//@formatter:on

		HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
		nearCacheMap = client.getMap("nearCacheMap");

		reader.run();
	}

	Runnable reader = new Runnable() {
		public void run() {
			while (true) {
				// 因为使用nearcache，所以每一次get，都会从本地cache获取（server的lastAccessTime不会出现变更）
				String value = nearCacheMap.get("test");
				logger.info("get value:{}", value);

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	};
}
